import { Alert, Linking, Platform } from 'react-native';
import {
  check,
  request,
  PERMISSIONS,
  RESULTS,
  Permission,
  PermissionStatus,
} from 'react-native-permissions';
import { InteractionManager } from 'react-native';
import i18n from '@/i18n';
import { navigationRef } from '@/navigation';

type PermissionResult = {
  status: PermissionStatus;
  granted: boolean;
  shouldShowRequestPermissionRationale?: boolean; // Android 特有
};

type CheckPermissionOptions = {
  requestIfNotGranted?: boolean; // 未授权时是否自动请求（默认 true）
};

class PermissionUtils {
  /**
   * 检查并确保权限可用
   * @param permission 权限常量，可直接传入iOS和安卓所有需要的权限
   * @param options 配置选项
   * @returns 权限结果对象
   */
  static async checkPermission(
    permission: Permission,
    options: CheckPermissionOptions = {
      requestIfNotGranted: true,
    }
  ): Promise<PermissionResult> {
    /// 自动筛选当前平台可用的权限
    const platformPermission = this.getPlatformPermission(permission);
    if (!platformPermission) {
      return {
        status: RESULTS.UNAVAILABLE,
        granted: false,
      };
    }

    let status: PermissionStatus = await check(platformPermission);
    const canRequestThisPermission = status === RESULTS.DENIED;

    if (options.requestIfNotGranted && canRequestThisPermission) {
      await InteractionManager.runAfterInteractions();
      if (Platform.OS === 'android') {
        await new Promise((resolve) => setTimeout(() => resolve(1), 500));
        await InteractionManager.runAfterInteractions(() => {
          const permissionDescription =
            PermissionUtils.getPermissionDescription(permission);
          // @ts-ignore
          navigationRef.navigate('PermissionDescription', {
            permissionDescriptions: [permissionDescription],
          });
        });
      }
      status = await request(platformPermission);
      if (Platform.OS === 'android') {
        navigationRef.goBack();
      }
    }

    return {
      status,
      granted: status === RESULTS.GRANTED,
      shouldShowRequestPermissionRationale:
        status === RESULTS.DENIED && Platform.OS === 'android',
    };
  }

  /**
   * 获取当前平台可用的权限常量
   * @param permission 跨平台权限常量
   * @returns 当前平台的实际权限
   */
  private static getPlatformPermission(
    permission: Permission
  ): Permission | null {
    const isAndroid = permission.includes('android');
    const isIOS = permission.includes('ios');

    if (Platform.OS === 'android' && isAndroid) return permission;
    if (Platform.OS === 'ios' && isIOS) return permission;

    // 尝试自动匹配跨平台权限（例如传入 CAMERA 自动选择平台）
    const permissionKey = permission.split('.').pop();
    if (!permissionKey) return null;

    const platformPermission =
      Platform.OS === 'android'
        ? (PERMISSIONS.ANDROID as any)[permissionKey]
        : (PERMISSIONS.IOS as any)[permissionKey];

    return platformPermission || null;
  }

  /**
   * 批量检查权限
   * @param permissions 权限数组
   * @returns 各权限的结果映射
   */
  static async checkMultiplePermissions(
    permissions: Permission[],
    options?: CheckPermissionOptions
  ): Promise<Record<Permission, PermissionResult>> {
    const results: Record<Permission, PermissionResult> = {} as any;

    for (const perm of permissions) {
      results[perm] = await this.checkPermission(perm, options);
    }

    return results;
  }

  static showPermissionNotGrantedAlert() {
    Alert.alert(i18n.t('message.enablePermission'), undefined, [
      {
        text: i18n.t('user.logOutCancel'),
      },
      {
        text: i18n.t('sys.app.go.2.settings'),
        onPress: Linking.openSettings,
      },
    ]);
  }
  /// 获取安卓系统所需要的权限申请的描述弹窗文案
  static getPermissionDescription(permission: Permission): string {
    switch (permission) {
      case PERMISSIONS.IOS.CAMERA:
      case PERMISSIONS.ANDROID.CAMERA:
        return i18n.t('sys.app.camera.use.reason');
      case PERMISSIONS.IOS.PHOTO_LIBRARY:
      case PERMISSIONS.ANDROID.READ_MEDIA_IMAGES:
        return i18n.t('message.enablePhotoLibraryPermission');
      case PERMISSIONS.IOS.LOCATION_ALWAYS:
      case PERMISSIONS.IOS.LOCATION_WHEN_IN_USE:
      case PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION:
      case PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION:
        return i18n.t('sys.app.location.use.reason');
      case PERMISSIONS.ANDROID.BLUETOOTH_SCAN:
      case PERMISSIONS.ANDROID.BLUETOOTH_CONNECT:
        return i18n.t('sys.app.bluetooth.use.reason');
      default:
        return '';
    }
  }
}

export default PermissionUtils;
export { PERMISSIONS, RESULTS };
export type { Permission, PermissionStatus, PermissionResult };
